import ResLoader from "./Libs/ResLoader";

const { ccclass, property } = cc._decorator;

@ccclass
export default abstract class BaseComponent extends cc.Component {
    public dynamicAsset: cc.Asset[] = [];

    //加载图片到Sprite
    public async loadImage(sprite: cc.Sprite, assetUrl: string, bundleKey?: string): Promise<void> {
        return ResLoader.load(assetUrl, cc.SpriteFrame, bundleKey).then((asset: cc.Texture2D | cc.SpriteFrame) => {

            this.addAssetRef(asset)

            let sf = asset instanceof cc.Texture2D ? new cc.SpriteFrame(asset) : asset
            sprite.spriteFrame = sf;
        })
    }

    // //加载图集到Sprite，不能加载远程图集
    // public loadAtlasImage(sprite: cc.Sprite, atlasUrl: string, frameName: string, bundleKey: string = null) {

    //     let bundle = bundleKey ? cc.assetManager.getBundle(bundleKey) : cc.resources

    //     if (!bundle) {
    //         throw new Error("loadImage:Bundle[" + bundleKey + "] 不存在")
    //     }

    //     return new Promise<void>((resolve, reject) => {
    //         let onComplete = (error: Error, atlas: cc.SpriteAtlas) => {
    //             if (error) {
    //                 throw new Error("loadAtlasImage:Asset[" + atlasUrl + "]加载错误:" + error)
    //             }

    //             ResMgr.addAssetRef(this.node.uuid, atlas)
    //             sprite.spriteFrame = atlas.getSpriteFrame(frameName);

    //             resolve();
    //         }

    //         bundle.load(atlasUrl, cc.SpriteAtlas, onComplete);
    //     })
    // }


    //加载预制体到节点
    public async loadPerfab(parentNode: cc.Node, prefabUrl: string, bundleKey?: string, hide?: boolean): Promise<cc.Node> {
        if (!parentNode || !parentNode.isValid) {
            throw new Error("loadPerfab[" + prefabUrl + "],父节点无效")
        }

        return ResLoader.load(prefabUrl, cc.Prefab, bundleKey).then((asset: cc.Prefab) => {

            this.addAssetRef(asset)

            let newNode: cc.Node = cc.instantiate(asset);
            newNode.active = !newNode;

            parentNode.addChild(newNode)
            return newNode
        })
    }

    //添加资源引用
    public addAssetRef(asset: cc.Asset) {
        if (!asset) return;
        if (!asset.isValid) return;

        asset.addRef();

        if (!this.dynamicAsset.includes(asset)) {
            this.dynamicAsset.push(asset);
        }
    }

    //删除资源引用
    public delAssetRef(asset: cc.Asset) {
        if (!asset) return;
        if (!asset.isValid) return;

        asset.decRef();

        if (asset.refCount == 0) {
            let index = this.dynamicAsset.indexOf(asset)
            if (index > -1) {
                this.dynamicAsset.splice(index, 1);
            }
        }

    }

    protected onDestroy(): void {
        this.dynamicAsset.forEach(asset => {
            asset.isValid && asset.decRef();
        })

        this.dynamicAsset.length = 0;
    }


}